package at.ac.tuwien.vpsbcm.spielzeugfabrik.alternativ.communication;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class LokTopicQueueConnHandler {
	
	private InitialContext jndiContext;
	private TopicConnectionFactory topicConnectionFactory;	
	private TopicConnection topicConnection;
	private TopicSession topicSession;
	private Topic topic;

	private static LokTopicQueueConnHandler lokTopicQueueConnHandler = new LokTopicQueueConnHandler();

	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

	private LokTopicQueueConnHandler() {
		// Singleton
	}

	public static LokTopicQueueConnHandler getInstance() {
		return lokTopicQueueConnHandler;
	}

	/**
	 * Create a JNDI API InitialContext object if none exists yet.
	 */
	private void createInitialContext() {
		try {
			if (jndiContext == null) {
				jndiContext = new InitialContext();
			
			}
		} catch (NamingException e) {
			System.out.println("Could not create JNDI API context: " + e.toString());
			e.printStackTrace();
			System.exit(1);
		}
	}

	/**
	 * Look up connection factory
	 */
	private void createLookupTopic() {

		try {
			if (this.topic == null) {
				
				topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup("LokTopicConnectionFactory");
				this.topic = (Topic) jndiContext.lookup("LokTopic");
			}
		} catch (NamingException e) {
			System.out.println("JNDI API lookup failed: " + e.toString());
			e.printStackTrace();
			System.exit(1);
		}
	}

	/**
	 * Create connection. Create session from connection; false means session is
	 * not transacted. Create publisher and text message. Send messages, varying
	 * text slightly. Finally, close connection.
	 */
	public TopicSession getConnection() {
		createInitialContext();
		createLookupTopic();
		try {
			if (topicSession == null) {
				topicConnection = topicConnectionFactory
						.createTopicConnection();
				topicSession = topicConnection.createTopicSession(false,
						Session.AUTO_ACKNOWLEDGE);
			}

			// topicPublisher = topicSession.createPublisher(topic);
			// message = topicSession.createTextMessage();

		} catch (JMSException e) {
			System.out.println("Exception occurred: " + e.toString());
		} 
		return topicSession;
	}

	public TopicPublisher getTopPublisher() throws JMSException {
		return topicSession.createPublisher(topic);
	}
	
	public TopicSubscriber getTopSubscriber() throws JMSException {
	    return topicSession.createSubscriber(topic);
	}
	
	public TopicConnection getTopicConnection() {
	    return topicConnection;
	}
	
	

}
